<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<cl-export-btn :columns="Table?.columns" />
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="upsertRef" />
		<el-dialog
			v-model="qrcodeDialogVisible"
			title="微信支付"
			width="300px"
			align-center
			:show-close="false"
			:close-on-click-modal="false"
		>
			<div class="flex justify-center">
				<img :src="qrcodeUrl" alt="支付二维码" style="width: 200px; height: 200px" />
			</div>
			<div class="text-center mt-4">请使用微信扫码支付</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="danger" @click="handleCancelPay">取消支付</el-button>
				</div>
			</template>
		</el-dialog>
	</cl-crud>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'order-info'
});

import { useCrud, useTable, useUpsert, useSearch, useForm } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, ref, watch } from 'vue';
import { useBase } from '/$/base';
import { useDict } from '/$/dict';
import StudentSelect from '/$/student/components/student-select.vue';
import ProductSelect from '/$/product/components/product-select.vue';
import ProductShow from '/$/order/components/product-show.vue';
import QRCode from 'qrcode';
import { ElMessage, ElMessageBox } from 'element-plus';

const { refs, setRefs } = useCool();
const { service } = useCool();
const { t } = useI18n();
const { user } = useBase();

// 添加响应式变量
const qrcodeDialogVisible = ref(false);
const qrcodeUrl = ref('');
const checkPaymentTimer = ref(null);

// 选项
const options = reactive({
	status: [
		{ label: t('待支付'), value: 0 },
		{ label: t('已支付'), value: 1 }
		// { label: t('已发货'), value: 2 },
		// { label: t('已完成'), value: 3 },
		// { label: t('已取消'), value: 4 }
	],
	payType: [
		{ label: t('微信'), value: 0 },
		{ label: t('现金'), value: 3 }
		// { label: t('支付宝'), value: 1 },
		// { label: t('银行卡'), value: 2 }
	],
	users: [
		{ label: t('王大锤'), value: 1 },
		{ label: t('李铁柱'), value: 2 },
		{ label: t('张翠花'), value: 3 }
	]
});

const disabled = ref(true);

// const Form = useForm();
// watch(() => refs.ProductIds, (newVal) => {
//     if (newVal) {
//         console.log('选择的商品IDs:', newVal);
//     }
// });

// 添加 upsertRef
const upsertRef = ref();
const productDetails = ref([]);
const productDetailsInfo = ref([]);
const discountDetails = ref([]);
const discountDetailsInfo = ref([]);
const orderInfo = ref([]); // 点击订单详情暂存订单信息
const tempOrderId = ref('');
const waitPay = ref(false);
const { dict } = useDict();

// 添加检查支付状态的方法
async function checkPaymentStatus(orderId) {
	const res = await service.order.info.checkPayStatus({ orderId });
	if (res.isPaid) {
		// 支付成功，清除定时器
		if (checkPaymentTimer.value) {
			clearInterval(checkPaymentTimer.value);
			checkPaymentTimer.value = null;
		}
		waitPay.value = false;
		// 关闭支付窗口
		qrcodeDialogVisible.value = false;
		// 关闭订单创建页面
		upsertRef.value?.close();
		ElMessage.success('支付成功');
		// 刷新列表
		refresh();
	}
}

// 添加计算金额的方法
async function calculateMoney(selectedData, couponId = null) {
	const params = {
		products: selectedData,
		couponId: couponId
	};
	const res = await service.product.product.getProductTotalMoney(params);
	upsertRef.value.form.totalAmount = res.totalMoney;
	upsertRef.value.form.discountAmount = res.discountMoney;
	upsertRef.value.form.payAmount = res.totalMoney - (upsertRef.value.form.discountAmount || 0);
	productDetails.value = res.details;
	discountDetails.value = res.discountDetails;
}

const currentSelectedProducts = ref([]);

// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t('选择用户'),
			prop: 'userId',
			component: {
				vm: StudentSelect,
				props: {
					modelValue: '' // 初始值
				}
			},
			span: 12,
			required: true,
			hidden: ({ scope }) => scope.userName
		},
		{
			label: t('购买用户'),
			prop: 'userName',
			component: { name: 'el-input', props: { min: 0, disabled } },
			required: true,
			span: 12,
			hidden: ({ scope }) => !scope.userName
		},
		{
			label: t('所属门店'),
			prop: 'shopId',
			component: {
				name: 'el-select',
				options: dict.get('Shop'),
				props: {
					disabled: true
				}
			},
			default: '',
			span: 12
		},
		{
			label: t('支付方式'),
			prop: 'payType',
			component: { name: 'el-radio-group', options: options.payType },
			value: 0,
			span: 12,
			required: true
		},
		// {
		// 	label: t('状态'),
		// 	prop: 'status',
		// 	component: {
		// 		name: 'cl-select',
		// 		props: { options: options.status }
		// 	},
		// 	value: 0,
		// 	span: 8
		// },
		{
			label: t('销售'),
			prop: 'salesName',
			component: {
				name: 'el-input',
				props: { disabled }
			},
			span: 12
		},
		{
			label: t('选择商品和套餐'),
			prop: 'ProductIds',
			palaceholder: t('选择商品和套餐'),
			component: {
				vm: ProductSelect,
				ref: setRefs('ProductIds'),
				props: {
					onSelectionChange: selectedData => {
						currentSelectedProducts.value = selectedData;
						calculateMoney(selectedData, upsertRef.value.form.coupon);
					}
				},
				style: {
					margin: '0px 0px 40px 0px'
				}
			},
			hidden: ({ scope }) => scope.userName
			// hidden: true
		},
		{
			label: t('优惠券'),
			prop: 'coupon',
			hook: 'number',
			component: {
				name: 'el-select',
				props: {
					min: 0,
					placeholder: '请先选择用户和商品',
					clearable: true,
					onChange: value => {
						if (currentSelectedProducts.value.length > 0) {
							calculateMoney(currentSelectedProducts.value, value);
						}
					}
				}
			},
			default: '',
			hidden: ({ scope }) => scope.userName
		},
		{
			label: t('总金额'),
			prop: 'totalAmount',
			hook: 'number',
			component: {
				name: 'el-input',
				props: { min: 0, disabled, placeholder: '请选择商品套餐' }
			},
			span: 8,
			default: 0,
			hidden: ({ scope }) => scope.userName
		},
		{
			label: t('优惠金额'),
			prop: 'discountAmount',
			hook: 'number',
			component: {
				name: 'el-input',
				props: { min: 0, disabled, placeholder: '请选择商品套餐' }
			},
			span: 8,
			default: 0,
			hidden: ({ scope }) => scope.userName
		},
		{
			label: t('支付金额'),
			prop: 'payAmount',
			hook: 'number',
			component: {
				name: 'el-input',
				props: { min: 0, disabled, placeholder: '请选择商品套餐' }
			},
			span: 8,
			default: 0,
			hidden: ({ scope }) => scope.userName
		},
		{
			prop: 'payImg',
			label: t('支付截图'),
			component: {
				name: 'cl-upload',
				props: {
					text: t('选择截图')
				}
			},
			hidden: ({ scope }) => scope.payType !== 3
		},
		{
			prop: 'productDetails',
			component: {
				vm: ProductShow,
				props: {
					test: 1,
					productDetailsInfo: productDetailsInfo,
					orderInfo: orderInfo
				}
			},
			hidden: ({ scope }) => !scope.userName
		}
	],
	async onInfo(data, { done }) {
		productDetailsInfo.value = data.productDetails;
		orderInfo.value = data;
		done(data);
	},
	async onOpen() {
		if (upsertRef.value.mode === 'add') {
			upsertRef.value.form.salesName = user.info?.name || '';
			upsertRef.value.form.shopId = user.info?.shop || '';
			currentSelectedProducts.value = [];
			waitPay.value = false;
		}
	},
	async onSubmit(data, { done, close, next }) {
		// 如果是现金支付则必须上传图片
		let status = 0;
		if (data.payType === 3 && !data.payImg) {
			ElMessage.error(t('请上传支付截图'));
			done();
			return;
		}
		if (data.payType === 3) {
			status = 1;
		} else {
			waitPay.value = true;
		}

		const result = await next({
			...data,
			sales: user.info?.id || '',
			status: status,
			productDetails: productDetails.value,
			discountDetails: discountDetails.value
		});
		// 如果选择的是微信支付则进行请求
		if (data.payType === 0) {
			const res = await service.order.info.payQrcode({ orderId: result.id });
			if (res.codeUrl) {
				tempOrderId.value = result.id; // 保存订单ID

				qrcodeUrl.value = await QRCode.toDataURL(res.codeUrl);
				qrcodeDialogVisible.value = true;

				// 开始轮询支付状态
				checkPaymentTimer.value = setInterval(() => {
					checkPaymentStatus(res.orderId);
				}, 3000); // 每3秒检查一次
			}
		}
	},
	async onClose(action, done) {
		if (action === 'save') {
			// 如果正在等待支付，则不关闭窗口
			if (waitPay.value) {
				return;
			}
			done();
		} else {
			done();
		}
	}
});

// 在 script setup 中添加 watch
watch(
	() => upsertRef.value?.form?.userId,
	async newUserId => {
		if (newUserId) {
			// 获取可用优惠券列表
			const res = await service.coupon.user.userCanUseCouponList({ userId: newUserId });
			// 更新优惠券选择器的选项
			upsertRef.value.items.find(item => item.prop === 'coupon').component.options = res.map(
				item => ({
					label: item.name,
					value: item.userCouponId
				})
			);
		}
	}
);

// 添加取消支付的处理方法
async function handleCancelPay() {
	try {
		await ElMessageBox.confirm('确认取消支付？', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		});

		// 用户点击确认，调用取消支付接口
		if (checkPaymentTimer.value) {
			clearInterval(checkPaymentTimer.value);
			checkPaymentTimer.value = null;
		}

		// 调用取消支付接口
		await service.order.info.cancelPay({ orderId: tempOrderId.value });
		ElMessage.success('已取消支付');
		qrcodeDialogVisible.value = false;
		waitPay.value = false;
		refresh();
	} catch (err) {
		// 用户点击取消，不做任何操作
	}
}

// 移除原有的 watch
watch(qrcodeDialogVisible, val => {
	if (!val && checkPaymentTimer.value) {
		// 窗口关闭时清除定时器
		clearInterval(checkPaymentTimer.value);
		checkPaymentTimer.value = null;
	}
});

// cl-table
const Table = useTable({
	columns: [
		{ type: 'selection' },
		{ label: t('订单ID'), prop: 'id', minWidth: 80 },
		{ label: t('姓名'), prop: 'userName', minWidth: 140 },
		{ label: t('渠道'), prop: 'userSource', minWidth: 140, dict: dict.get('Source') },
		{ label: t('手机号'), prop: 'userPhone', minWidth: 140 },
		{
			label: t('总金额'),
			prop: 'totalAmount',
			minWidth: 140,
			sortable: 'custom',
			formatter: row => Math.floor(row.totalAmount)
		},
		{
			label: t('销售'),
			prop: 'salesName',
			minWidth: 140,
			sortable: 'custom'
		},
		{
			label: t('支付方式'),
			prop: 'payType',
			minWidth: 120,
			dict: options.payType
		},
		{
			label: t('支付状态'),
			prop: 'status',
			minWidth: 120,
			dict: options.status
		},
		{
			label: t('店铺'),
			prop: 'shopId',
			minWidth: 120,
			dict: dict.get('Shop')
		},
		{
			label: t('订单时间'),
			prop: 'createTime',
			minWidth: 100,
			sortable: 'custom',
			component: {
				name: 'cl-date-text',
				props: {
					format: 'MM-DD HH:mm'
				}
			}
		},
		{ label: t('商品内容'), prop: 'productName', showOverflowTooltip: true },
		{ type: 'op', buttons: ['info'] }
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'status',
			component: {
				name: 'cl-select',
				props: { options: options.status, placeholder: '支付状态' }
			}
		},
		{
			prop: 'shopId',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Shop'), placeholder: '店铺' }
			}
		},
		{
			prop: 'payType',
			component: {
				name: 'cl-select',
				props: { options: options.payType, placeholder: '支付方式' }
			}
		},
		{
			prop: 'phone',
			component: {
				name: 'el-input',
				props: { placeholder: '手机号' }
			}
		},
		{
			prop: 'name',
			component: {
				name: 'el-input',
				props: { placeholder: '姓名' }
			}
		}
	]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.order.info,
		async onRefresh(params, { next, done, render }) {
			if (user.info?.id != 1) {
				params.shopId = user.info?.shop || '';
			}
			console.log(user.info);
			// 如果没有指定状态筛选，默认筛选已支付状态
			if (!params.status && params.status !== 0) {
				params.status = 1; // 1 表示已支付状态
			}
			const { list } = await next(params);

			// 渲染数据
			render(list);
		}
	},
	app => {
		app.refresh();
	}
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
</script>
